package session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Session 生命周期
 */
public class S3_SessionLife extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /*
        session生命周期
        I)指的是两次访问session的最大间隔 默认30分钟
        II)如果在session没有过期的情况下，操作session，则会重新开始计算生命周期
        III)session是否过期是由服务端来维护和管理的
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("S3_SessionLife 被调用...");

        //1.创建session
        HttpSession session = req.getSession();
        System.out.println("创建的sessionId=" + session.getId());
        //设置生命周期 60s
        session.setMaxInactiveInterval(60);

        //删除session对象的某个属性
//        session.removeAttribute("email");
        //立即删除session
//        session.invalidate();


        session.setAttribute("email", "jack@qq.com");

        //2.回送浏览器
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>创建session成功~，设置生命周期60s</h1>");
        writer.flush();
        writer.close();
    }
}
